package com.weixin.service.Impl;

import com.weixin.dto.OrderDto;
import com.weixin.enums.ResultEnum;
import com.weixin.exception.SellException;
import com.weixin.service.BuyerService;
import com.weixin.service.OrderMasterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author CJunGod
 * @create 2020-03-02 15:49
 **/
@Slf4j
@Service
public class BuyerServiceImpl implements BuyerService {

    @Resource
    private OrderMasterService orderMasterService;

    @Override
    public OrderDto findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid, orderId);
    }

    @Override
    public OrderDto cancelOrder(String openid, String orderId) {
        OrderDto dto = checkOrderOwner(openid, orderId);
        if(dto == null){
            log.error("{取消订单}根据openid买家查询的订单为空");
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        return orderMasterService.cancel(dto);
    }

    private OrderDto checkOrderOwner(String openid, String orderId){
        OrderDto one = orderMasterService.findOne(orderId);
        if (one == null){
            log.error("查询订单内容为空");
            return null;
        }
        //判断是否是买家自己的订单
        if(!one.getMaster().getBuyerOpenid().equalsIgnoreCase(openid)){
            log.error("{查询订单}订单的openid不一致,openid={}",openid);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }

        return one;
    }
}
